#ifdef ORATR_USE_HTTP

#include "http.hpp"
#include "http_download.h"

bool CheckHTTPRequestString(string str) {
	return (str.find_first_of(":/@?&") != string::npos);
}

void ParseHTTPRequestString(string str, Variable &host, Variable &rfile, Variable &port) {
	UNUSED host;
	port = 80;
	rfile = (Variable)"/";
	// Remove any http://, ftp://, etc
	size_t pos;
	if((pos = str.find("://")) != string::npos) {
		str.erase(0,pos+3);
	}
	
	// Parse the port or remote file
	pos = str.find_first_of(":/");
	if(pos != string::npos) {
		host = str.substr(0,pos);
		str = str.substr(pos);
		if(str[0] == ':') {
			// Port
			pos = str.find_first_of("/");
			if(pos != string::npos) {
				port = str.substr(1,pos);
				port = port.i;
				str = str.substr(pos);
				rfile = str;
			} else {
				port = str.substr(1);
				port = port.i;
			}
		} else {
			// Remote file
			rfile = str;
		}
	} else {
		host = str;
	}
	return;
}

Variable bi_http(vector<Variable> &argv, Environment& env)
{
	Variable ret;
	unsigned argc = argv.size();
	Variable host, rfile, port;
	if(argc < 2 || argc > 4) {
		throw_error(ERROR_ARGUMENTCOUNT);
	}
	host = argv[1];
	env.verify(host);
	if(argc == 2 && CheckHTTPRequestString(host.str)) {
		// TODO: Get this working
		ParseHTTPRequestString(host.str,host,rfile,port);
	} else {
		if(argc > 2) {
			rfile = argv[2];
			env.verify(rfile);
			if(!rfile.str.size() || rfile.str[0] != '/') {
				rfile.str = '/' + rfile.str;
			}
		} else {
			rfile = (Variable)"/";
		}
		if(argc==4) {
			port = argv[3];
			env.verify(port);
		} else {
			port = 80;
		}
	}
	if(host.type != tString || rfile.type != tString || port.type != tNumeric) {
		cout<< "ERROR: Syntax for http is:\n\t"
			<< "http [host]\n\t"
			<< "http [host] [remote file]\n\t"
			<< "http [host] [remote file] [port]\n";
		return ret;
	}
	CHttpDownload *pDownloader = new CHttpDownload();
	pDownloader->Create();
	if(!pDownloader->Connect( host.str.c_str(), (int)port.i )) {
		throw_error(ERROR_SOCKET);
	}
	string tmp;
	int err = pDownloader->DownloadArray(rfile.str.c_str(), tmp);
	if(err) {
		cout << "HTTP error " << hex << err << dec << endl;
		switch(err) {
		case SOCKET_ERROR:
			cout << "Socket error";
			break;
		case HTTPERR_REQUEST:
			cout << "Request error";
			break;
		default:
			cout << "Unimplemented error";
			break;
		}
		cout << endl;
		//throw_error(ERROR_SOCKET);
	}
	pDownloader->Close();
	ret = (Variable)tmp;
	return ret;
}

#endif
